package com.zhenyi.fenda.controller;

import java.util.Collections;
import java.util.Date;

import com.fenda.common.model.FdConsult;
import com.fenda.common.model.FdMaster;
import com.fenda.common.model.FdMessage;
import com.fenda.common.model.FdNotification;
import com.fenda.common.model.FdRoom;
import com.fenda.common.model.FdUser;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhenyi.fenda.core.ws.Msg;
import com.zhenyi.fenda.core.ws.WSServer;

import cn.hutool.core.lang.Singleton;
import cn.hutool.json.JSONObject;

public class ChatController extends FDController {

	protected WSServer server = Singleton.get(WSServer.class);

	private void sendToRoom(String roomCode, Msg msg) {
		Long roomId = hashId.decode(roomCode)[0];
		FdRoom room = FdRoom.dao.findById(roomId);
		FdUser user = FdUser.dao.findById(room.getUserId());
		msg.setConversation(roomCode);
		if (user != null) {
			server.send(msg.toJson(), user.getWsUid());
		}
		FdUser master = FdUser.dao.findById(room.getMasterId());
		if (master != null) {
			server.send(msg.toJson(), master.getWsUid());
		}

	}

	public void send() {
		String json = HttpKit.readData(getRequest());
		JSONObject jsonObject = new JSONObject(json);
		String code = jsonObject.getStr("code");
		String content = jsonObject.getStr("content");
		Long roomId = hashId.decode(code)[0];
		FdRoom room = FdRoom.dao.findById(roomId);

		FdUser user = getUser();

		FdMessage message = new FdMessage();
		message.setFromUserId(user.getId());
		message.setContent(content);
		message.setAddTime(new Date());
		message.setRoomId(roomId);
		message.save();
		sendToRoom(code, message.getMsg());

		Long id;
		Kv cond = Kv.create();
		FdNotification fdNotification;
		if (room.getUserId().equals(user.getId())) {
			id = room.getMasterId();
		} else {
			id = room.getUserId();
		}
		cond.set("userId", id);
		cond.set("roomId", roomId);
		SqlPara sqlPara = Db.getSqlPara("findNotificationRoom", cond);
		fdNotification = FdNotification.dao.findFirst(sqlPara);
		if (fdNotification == null) {
			fdNotification = new FdNotification();
			fdNotification.setUserId(id);
			fdNotification.setContent("咨询信息提醒");
			fdNotification.setType(NOTIFICACATION_ROOM);
			fdNotification.setRoomId(roomId);
			fdNotification.setAddTime(new Date());
			fdNotification.save();
		} else {
			fdNotification.setAddTime(new Date());
			fdNotification.update();
		}
		renderSuccess();
	}

	/**
	 * 获取聊天记录
	 */
	@Clear
	public void message() {
		String code = getPara(0);
		int pageNumber = getParaToInt(1, 1);
		if (StrKit.isBlank(code)) {
			renderFailure();
			return;
		}
		Long roomId = hashId.decode(code)[0];
		Kv cond = Kv.by("roomId", roomId);
		SqlPara sqlPara = Db.getSqlPara("FDFindMessageInRoom", cond);
		Page<Record> list = Db.paginate(pageNumber, pageSize, sqlPara);
		setAttr("list", list);
		renderJson(list);
	}

	@Override
	public void index() {
		connect();
	}

	public void connect() {
		// String code = "Bdlqbl";
		String code = getPara(0);
		int pageNumber = getParaToInt(1, 1);// 聊天记录当前页
		if (StrKit.isBlank(code)) {
			renderFailure();
			return;
		}
		Long roomId = hashId.decode(code)[0];

		// 聊天记录
		Kv cond = Kv.by("roomId", roomId);
		SqlPara sqlPara = Db.getSqlPara("FDFindMessageInRoom", cond);
		Page<Record> list = Db.paginate(pageNumber, pageSize, sqlPara);

		FdRoom room = FdRoom.dao.findById(roomId);
		Long masterId = room.getMasterId();
		Long userId = room.getUserId();
		FdUser user = getUser();
		if (!(masterId.equals(user.getId()) || userId.equals(user.getId()))) {
			renderFailure();
			return;
		}
		if (room.getExpire().getTime() < new Date().getTime()) {
			Kv kv = Kv.by("userId", user.getId());
			kv.set("roomId", roomId);
			SqlPara sqlPara2 = Db.getSqlPara("findCompleteRoom", kv);
			Long fdConsultId = Db.findFirst(sqlPara2).getLong("id");
			if (fdConsultId == null) {
				renderFailure();
				return;
			}
			FdConsult fdConsult = FdConsult.dao.findById(fdConsultId);
			fdConsult.setIsFinish(1);
			fdConsult.update();
			renderFailure();
			return;
		}
		FdConsult consult = FdConsult.dao.searchFirst("roomId", roomId);
		if (consult == null) {
			renderFailure();
			return;
		}
		// Long consultId = room.get
		setInfoItem(room);
		renderSuccess();

		setAttr("code", code);
		setAttr("user", user);
		FdMaster master = FdMaster.dao.findById(user.getId());
		boolean isMaster = master != null;

		if (isMaster) {
			FdUser toUser = FdUser.dao.findById(room.getUserId());
			setAttr("toUser", toUser);
		} else {
			FdUser toUser = FdUser.dao.findById(room.getMasterId());
			setAttr("toUser", toUser);
		}
		setAttr("isMaster", isMaster ? 1 : 0);

		Collections.reverse(list.getList());
		setAttr("list", list);
		setAttr("wsHost", PropKit.get("WS_HOST", "ws://192.168.50.18:8989/ws"));
		render("/fd/chat.html");
	}

}
